/*该类接受一个URL路径和一个规范化好的json请求体，并处理返回结果给调用者。*/
const logger = require('./Logger')
const Normalize = require('./Normalize')
const HandlerResolver = require('./HandlerResolver')

class RequestHandler {
  constructor (handlerResolver) {
    this._handlerResolver = handlerResolver
  }

  handle (params) {
    let { path, query, data } = params
    try {
      const normalizerName = query.normalizer || 'simple' // 从query中获取规范器
      data = Normalize(params, normalizerName)
      logger.verbose(`使用${normalizerName} normalizer处理，结果为：`, data)
      let handler = this._handlerResolver.resolve(path, data)
      return handler.handle(data)
    } catch (err) {
      if (err instanceof Normalize.LoadedError) {
        return { code: 'normalizer_not_found', message: `缺失normalizer插件：${normalizerName}.` }
      } else if (err instanceof Normalize.NormalizeError) {
        logger.error('执行normalize时出错，reason：', err.reason)
        return { code: 'normalize_error', message: '执行normalize时出错。', reason: err.reason.message }
      } else if (err instanceof HandlerResolver.ResolveError && err.code === 'PATH_NOT_RESOLVED') {
        return { code: 'config_not_found', message: `缺失路径${path}对应的配置文件` }
      } else if (err instanceof HandlerResolver.ResolveError && err.code === 'HANDLER_NOT_RESOLVED') {
        return { code: 'handler_not_matched', message: '配置文件存在，但文件内列出handler配置均不匹配' }
      } else {
        throw err
      }
    }
  }
}

module.exports = RequestHandler
